package com.cwt_taxi_xa;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwt_taxi_xa.adapter.AdapterOnClickListener;
import com.cwt_taxi_xa.adapter.GridAdapter;
import com.cwt_taxi_xa.adapter.SettingItem;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.util.AppBiz;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DownloadUtil;
import com.cwt_taxi_xa.util.FileOper;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.Tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class FunctionActivity extends CWTBaseActivity implements OnClickListener{

	private GridView gridview;
	private List<SettingItem> dataList;
	private GridAdapter adapter;
	private TextView showtime;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_function);

		setupViews();
		//addListener();
		initData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	private void setupViews() {
		// TODO Auto-generated method stub
		showtime = (TextView)findViewById(R.id.showtime);
		showtime.setVisibility(View.VISIBLE);
		showtime.setText("设置");

		gridview = (GridView) findViewById(R.id.gridview);
		gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
	}

	private void addListener() {
		// TODO Auto-generated method stub
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
									long arg3) {
				// TODO Auto-generated method stub
				doNext(position);
			}
		});
	}

	protected void doNext(int position) {
		// TODO Auto-generated method stub

	}

	private void initData() {
		//图标下的文字
		dataList = new ArrayList<>();
		dataList.add(new SettingItem("设备维护",R.drawable.ic_star,onClickValidationPass));
		//dataList.add(new SettingItem("计价器",R.drawable.ic_star,onClickMeter));
		dataList.add(new SettingItem("版本信息",R.drawable.ic_star,onClickVersionInfo));
		dataList.add(new SettingItem("GPS信息",R.drawable.ic_star,onClickShowGpsInfo));

		dataList.add(new SettingItem("自检报告",R.drawable.ic_star,onClickPower));
		dataList.add(new SettingItem("亮度调节",R.drawable.ic_star,onClickBrightnessSetting));
		dataList.add(new SettingItem("设备信息",R.drawable.ic_star,onClickDevicesInfo));

		dataList.add(new SettingItem("切换声道",R.drawable.ic_star,onClickSound));
		dataList.add(new SettingItem("升级导航",R.drawable.ic_star,onClickNavigation));
		dataList.add(new SettingItem("导出日志",R.drawable.ic_star,onClickOutport));

		dataList.add(new SettingItem("音量设置",R.drawable.ic_star,onClickVolume));
		//dataList.add(new SettingItem("蓝牙",R.drawable.ic_star,onClickBluetooth));
		//dataList.add(new SettingItem("空调",R.drawable.ic_star,onClickConditioning));

		dataList.add(new SettingItem("车辆信息",R.drawable.ic_star,onClickCarInfo));
		//dataList.add(new SettingItem("声耕升级测试",R.drawable.ic_star,onClickVoice));

		adapter = new GridAdapter(this,dataList);
		gridview.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		/*switch (v.getId()) {
		case R.id.zhongbiaoLin:
			break;
		}*/
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub

	}

	/*public class FunctionInfo{

		private String name;
		private int id;
		private int iconId;

		public FunctionInfo() {
			super();
		}

		public FunctionInfo(String name, int id, int iconId) {
			super();
			this.name = name;
			this.id = id;
			this.iconId = iconId;
		}

		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public int getIconId() {
			return iconId;
		}
		public void setIconId(int iconId) {
			this.iconId = iconId;
		}
	}*/



	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1001){
				if (progressDialog != null && progressDialog.isShowing()) {
					try {
						progressDialog.dismiss();
					} catch (Exception e) {
					}
				}
				//下载完成进行相关逻辑操作
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "高德4.0.apk")), "application/vnd.android.package-archive");
				startActivity(intent);
			}
			if(msg.what==1002){
				int progress = (int) msg.obj;
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.setProgress(progress);
				}
			}
			if(msg.what==1003){
				if (progressDialog != null && progressDialog.isShowing()) {
					try {
						progressDialog.dismiss();
					} catch (Exception e) {
					}
				}
				Toast.makeText(FunctionActivity.this, "下载出错", 1500).show();
			}
		};
	};

	public void downFile(String url) {
		DownloadUtil.get().download(url, Environment.getExternalStorageDirectory().getAbsolutePath(), "高德4.0.apk", new DownloadUtil.OnDownloadListener() {
			@Override
			public void onDownloadSuccess(File file) {
				handler.sendEmptyMessage(1001);
			}

			@Override
			public void onDownloading(int progress) {
				handler.sendMessage(handler.obtainMessage(1002, progress));
			}

			@Override
			public void onDownloadFailed(Exception e) {
				//下载异常进行相关提示操作
				handler.sendEmptyMessage(1003);
				e.printStackTrace();
			}
		});

	}




	public void downloadFile1(String url) {
		try{
			//下载路径，如果路径无效了，可换成你的下载路径
//			 String url = "http://c.qijingonline.com/test.mkv";
			String path = Environment.getExternalStorageDirectory().getAbsolutePath();

			final long startTime = System.currentTimeMillis();
			Log.i("DOWNLOAD","startTime="+startTime);
			//下载函数
			String filename=url.substring(url.lastIndexOf("/") + 1);
			//获取文件名
			URL myURL = new URL(url);
			URLConnection conn = myURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			int fileSize = conn.getContentLength();//根据响应获取文件大小
			if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
			if (is == null) throw new RuntimeException("stream is null");
			File file1 = new File(path);
			if(!file1.exists()){
				file1.mkdirs();
			}
			//把数据存入路径+文件名
			FileOutputStream fos = new FileOutputStream(path+"/"+filename);
			byte buf[] = new byte[1024];
			int downLoadFileSize = 0;
			do{
				//循环读取
				int numread = is.read(buf);
				if (numread == -1)
				{
					break;
				}
				fos.write(buf, 0, numread);
				downLoadFileSize += numread;
				//更新进度条
			} while (true);
			Log.i("DOWNLOAD","download success");
			Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
			is.close();
		} catch (Exception ex) {
			Log.e("DOWNLOAD", "error: " + ex.getMessage(), ex);
		}
	}

	private AdapterOnClickListener onClickValidationPass = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ValidationPassWord.class));
		}
	};

	private AdapterOnClickListener onClickVersionInfo = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ShowVersionInfo.class));
		}
	};
	private AdapterOnClickListener onClickShowGpsInfo = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ShowGpsInfo.class));
		}
	};
	private AdapterOnClickListener onClickPower = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityPower.class));
		}
	};
	private AdapterOnClickListener onClickBrightnessSetting = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, BrightnessSetting.class));
		}
	};
	private AdapterOnClickListener onClickDevicesInfo = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityInfo.class));
		}
	};
	private AdapterOnClickListener onClickSound = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			if(MyStatus.vichl==1){
				MCUUtil.selecterVic(2);
				TTsFunction.speakText("系统声道");
				Toast.makeText(FunctionActivity.this, "系统声道", 1000).show();
			}else if(MyStatus.vichl==2){
				MCUUtil.selecterVic(3);
				Toast.makeText(FunctionActivity.this, "AUX声道", 1000).show();
			}else if(MyStatus.vichl==3){
				MCUUtil.selecterVic(4);
				Toast.makeText(FunctionActivity.this, "IP通话声道", 1000).show();
			}else if(MyStatus.vichl==4){
				MCUUtil.selecterVic(1);
				Toast.makeText(FunctionActivity.this, "FM声道", 1000).show();
			}
		}
	};

	private AdapterOnClickListener onClickNavigation = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			try {
				PackageManager packageManager = getPackageManager();
				boolean isup = false;
				PackageInfo packageInfo = null;
				try {
					packageInfo = packageManager.getPackageInfo("com.autonavi.amapauto", 0);
					isup = packageInfo.versionCode==547;
					AppLog.e("当前高德版本-"+packageInfo.versionCode);
					AppLog.e("当前高德版本-"+packageInfo.versionName);
				} catch (Exception e) {
					isup = true;
				}
				if(isup){
					progressDialog = new ProgressDialog(FunctionActivity.this);
					progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					progressDialog.setTitle("正在下载");
					progressDialog.setMessage("请稍后...");
					progressDialog.setProgress(0);
					progressDialog.setMax(100);
					progressDialog.show();
					progressDialog.setCancelable(false);
					new Thread(new Runnable() {
						@Override
						public void run() {
							downFile("https://mapdownload.autonavi.com/amapauto/apk/autobasic/guanwangV4.0.0.6130_FRSE3276F0.apk");
							//downFile("http://114.116.66.51:8080/upload/guanwang.apk");
						}
					}).start();
				}else{
					Toast.makeText(FunctionActivity.this, "当前已经是最新版本", 1500).show();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private AdapterOnClickListener onClickOutport = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			String copyRootPath = "/mnt/usbhost/Storage00";
			try {
				long sdsize = 0;
				for (int i = 0; i < 10; i++) {
					copyRootPath = copyRootPath.substring(0, copyRootPath.length() - 1) + i;
					sdsize = FileOper.getSDAllSize(copyRootPath);
					if (sdsize > 1) {
						break;
					}
				}
				if (sdsize < 20) {
					MainApplication.topActivity.myToast("未检测到U盘");
					TTsFunction.speakText("未检测到U盘");
				} else {
					File f = new File("/mnt/sdcard/导航终端日志文件");
					if(f.exists()){
						Tools.copyDir(f.getAbsolutePath(), copyRootPath+"/导航终端日志文件");
					}
					MainApplication.topActivity.myToast("导出结束");
					TTsFunction.speakText("导出结束");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private AdapterOnClickListener onClickConditioning = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityConditioning.class));
		}
	};

	private AdapterOnClickListener onClickCarInfo = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityCarInfo.class));
		}
	};

	private AdapterOnClickListener onClickVolume= new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityVolume.class));
		}
	};

	private AdapterOnClickListener onClickMeter = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityMeter.class));
		}
	};

	private AdapterOnClickListener onClickBluetooth = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			try {
				new AppBiz(FunctionActivity.this).launchApp("com.blink.blinkdemo");
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(FunctionActivity.this, "应用未开安装", Toast.LENGTH_SHORT).show();
			}

		}
	};

	private AdapterOnClickListener onClickVoice = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(FunctionActivity.this, ActivityVoice.class));
		}
	};
}
